package rabbitas{
	import flash.events.EventDispatcher;
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import rabbitas.attributes.AttributeName;
	import rabbitas.events.RabbitObjectInitEvent;
	/**
	 * @author martindyrby
	 */
	public class LiveCycleManager extends EventDispatcher{
		private var pendingInstances:Array;
		
		public function LiveCycleManager() {
			pendingInstances = new Array();
		}
		
		public function initialize(instance : *, def : XML) : void {
			var initMethod:String = def.@[AttributeName.INIT_METHOD];
			var initCompleteEvent:String = def.@[AttributeName.INIT_COMPLETE_EVENT];
			
			if (initMethod != "") {
				var f : Function = instance[initMethod];
				f.apply();

				if(initCompleteEvent!=""){
					pendingInstances.push(instance);
					if(instance is IEventDispatcher){
						IEventDispatcher(instance).addEventListener(initCompleteEvent,initCompleteHandler);
					}
				} else if(Object(instance).hasOwnProperty("registerInitCompleteCallback")) {
					pendingInstances.push(instance);
					instance["registerInitCompleteCallback"](onInitComplete);
				}
			}
		}
		
		public function instanceIsPendingInit(instance:Object):Boolean{
			for(var i:int=0; i<pendingInstances.length;i++){
				if(pendingInstances[i]==instance) return true;
			}
			
			return false;
		}

		private function onInitComplete(instance:*):void {
			for(var i:int=0; i<pendingInstances.length;i++){
				if(pendingInstances[i]==instance) {
					pendingInstances.splice(i,1);
					break;
				}
			}			
			dispatchEvent(new RabbitObjectInitEvent(RabbitObjectInitEvent.INIT_COMPLETE, instance));
		}
		
		private function initCompleteHandler(event:Event):void{
			onInitComplete(event.currentTarget);
		}
	}
}
